package scr.springbootcaffeineredis;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import io.lettuce.core.RedisClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;

import java.util.concurrent.TimeUnit;

@Configuration
@Slf4j
public class RedisCilentConfiguration {
    @Bean
    public CommandLineRunner init(@Autowired CacheFrontendContext cacheFrontendContext) {
        return new CommandLineRunner() {
            @Override
            public void run(String... args) throws Exception {
                while (true) {
                    cacheFrontendContext.check();
                    Thread.sleep(1000);
                }
            }
        };
    }

    @Bean
    public Cache<String, Object> localCache() {
        return Caffeine.newBuilder()
                .expireAfterWrite(5, TimeUnit.MINUTES)
                .initialCapacity(100)
                .maximumSize(1000)
                .build();
    }

    @Bean
    public RedisClient redisClient(@Autowired LettuceConnectionFactory lettuceConnectionFactory) {
        RedisClient redisClient = (RedisClient) lettuceConnectionFactory.getNativeClient();
        return redisClient;
    }

    @Bean
    public CacheFrontendContext cacheFrontendContext(@Autowired RedisClient redisClient, @Autowired Cache cache) {
        return new CacheFrontendContext(redisClient, cache);
    }
}
